import 'package:flutter/material.dart';
import 'dart:async';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_channel_demo/utils/tools.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

class WebviewPage extends StatefulWidget {
  Map arguments;

  WebviewPage({super.key, required this.arguments});

  @override
  State<WebviewPage> createState() => _WebviewPageState();
}

class _WebviewPageState extends State<WebviewPage> {
  WebViewController? _webviewController;
  late final String _title;
  Future<bool> _exitApp(BuildContext context) async {
    if (await _webviewController!.canGoBack()) {
      debugPrint("onWill goBack");
      _webviewController!.goBack();
      return Future.value(false);
    } else {
      debugPrint("_exit will not go back");
      return Future.value(true);
    }
  }

  @override
  void initState() {
    setState(() {
      _title = widget.arguments["title"] ?? 'webview';
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(appBar: AppBar(title: Text(_title)), body: h5WebView()),
        onWillPop: () => _exitApp(context));
  }

  Widget h5WebView() {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return AndroidView(
        viewType: 'plugins.flutter.io/custom_platform_view',
        creationParams: {'url': widget.arguments['url'], 'text': _title},
        creationParamsCodec: const StandardMessageCodec(),
        // viewType: "<platform-view-type>",
      );
    } else {
      return WebView(
        initialUrl: widget.arguments['url'],
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _webviewController = webViewController;
        },
        navigationDelegate: (NavigationRequest request) {
          if (request.url.indexOf(".ess.tencent.cn/m/") > -1) {
            debugPrint("即将打开 ${request.url}");
            switchTab(context, '/contracts');
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      );
    }
  }
}
